import { useState, useContext } from 'react';
import useDeepCompareEffect from 'use-deep-compare-effect';
import { ContentContext } from '../PublicComponents/Context/contextLoading';
import moment from 'moment';

// moment转字符传&&字符串去前后空格
function formatString(v: any) {
  if (v instanceof moment) {
    // @ts-ignore
    v = v.format('YYYY-MM-DD');
  }
  if (v instanceof String) {
    v = v.trim();
  }
  return v;
}

// 'a,b,c':[1,2,3] 转化为 a:1,b:2,c:3
function formatFormValues(values: any) {
  const split = ',';
  Object.keys(values).forEach((k) => {
    if (k.includes(split)) {
      k.split(split).forEach((key, index) => {
        values[key] = formatString(values[k][index]);
      });
      values[k] = undefined;
    } else {
      values[k] = formatString(values[k]);
    }
  });
  return values;
}

/**
 *
 * @param service  请求接口方法
 * @param deps  请求参数依赖 数组类型 可将参数分解成多个依赖对象
 * @param initial 初始值
 * @param unmount 页面卸载执行方法
 * @returns {unknown} 请求结果值
 */
const useMountData = (service: any, deps: any = [], cb: any, initial: any = {}, unmount?: any) => {
  const [data, setData] = useState(initial);
  // const { setIsLoading } = useContext(ContentContext) || {};
  const { setIsLoading } = useContext(ContentContext) || {};
  // console.log(ContentContext);
  // console.log(setIsLoading);
  useDeepCompareEffect(() => {
    // 将请求依赖合并成请求参数
    // @ts-ignore
    const { waitRun, ...params } = deps.reduce((p, c) => ({ ...p, ...c }), {
      waitRun: false,
    });
    // @ts-ignore
    let setFn = (resp, par) => {
      // @ts-ignore
      resp && setData(resp, par);
    };
    // @ts-ignore
    const getData = async (ser, par) => {
      const resp = await ser(par, setIsLoading);
      resp?.success && cb && cb(resp, par);
      // @ts-ignore
      setFn && setFn(resp);
    };

    if (waitRun && data !== undefined) {
      // @ts-ignore
      setData(undefined);
    } else if (!waitRun) {
      getData(service, formatFormValues(params));
    }

    return () => {
      // @ts-ignore
      setFn = undefined;
      unmount && unmount();
    };
  }, deps);

  return data;
};

export default useMountData;
